package dubbo.learn;

import dubbo.learn.handler.ServerChannelInitializer;
import dubbo.learn.utils.NamedThreadFactory;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.ClassPathXmlApplicationContext;

@Slf4j
public class Bootstrap {

    private static final NamedThreadFactory namedThreadFactoryForAcceptor = new NamedThreadFactory("netty_acceptor");

    private static final NamedThreadFactory namedThreadFactoryForClientChannel = new NamedThreadFactory("netty_worker");

    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("provider.xml");
        System.out.println(context);

        ServerBootstrap server = new ServerBootstrap();
        NioEventLoopGroup parentGroup = new NioEventLoopGroup(1,namedThreadFactoryForAcceptor);
        NioEventLoopGroup childGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors(),namedThreadFactoryForClientChannel);
        try {
            server.group(parentGroup, childGroup)
                    .channel(NioServerSocketChannel.class)
                    .localAddress(8081)
                    .childHandler(new ServerChannelInitializer());

            log.info("Netty server has started on port : " + 8081);

            server.bind().sync().channel().closeFuture().sync();
        }catch (Exception e){
            log.error("exception");
        }
        finally {
            parentGroup.shutdownGracefully();
        }
    }


}
